var router = require('express').Router();
var util = require('util');
var uuid = require('node-uuid');
var cookie = require('cookie');
var LRU = require('lru-cache');
var EventProxy = require('eventproxy');
var async = require('async');

var Consts = require('../consts');
var resultJson = require('../result-json');
var Utils = require('../utils');
var logger = require('../models/logger');
var User = require('../models/User');
var CryptoJS = require("../CryptoJS");
var SMSSend = require('../sms-utils');
var Message = require('../models/Message');

var options = {
		max: 500,
		maxAge: 1000 * 60 * 60
	},
	cache = LRU(options);

router.post('/', function(req, res) {
	res.send('respond with a resource');
});

//注册
router.post('/reg', function(req, res) {
	var user = req.body;
	user.category = user.category || Consts.UTYPE.CHINESE;
	if (!user.phone || !user.password)
		return res.send(resultJson(3));

	user.password = Utils.MD5(user.password);
	User.count({
		phone: user.phone
	}, function(err, cnt) {
		if (err)
			return res.send(resultJson(2));
		if (cnt)
			return res.send(resultJson(102));

		var newUser = new User(user);
		newUser.save(function(err) {
			if (err)
				return res.send(resultJson(2));
			return res.send(resultJson(0, newUser));
		});
	});
});

router.post("/yanzhengma", function(req, res, next) {
	var phone = req.body.phone;
	console.log(phone);
	var num = Utils.random();
	var msg = "验证码为"+num+"，1分钟内有效，请及时输入完成验证【华鑫杰瑞公司】";
	Utils.yanzhengma(phone, msg, function(result) {
		console.log("result:"+result);
		var obj = JSON.parse(result);
		console.log(obj.result.data);
		if(obj.result.data == "ok"){
			res.send(resultJson(0, {"type":"ok","phone":phone,"num":num}));
		}
		if(obj.result.data == "error"){
			res.send(resultJson(0, {"type":"error"}));
		}
		
	});
});




router.post('/detail', function(req, res) {
	var _id = req.body._id;
	console.log("user:id="+_id);
	if (!_id)
		return res.send(resultJson(3));

	User.findOne({
		_id: _id
	}).exec(function(err, user) {
		if (err) {
			logger.error(err);
			return res.send(resultJson(2));
		}
		user = JSON.parse(JSON.stringify(user));
		var length = user.friends && user.friends.length || 0;
		var newFriends = [];
		for(var i=0;i<length;i++){ 
		    if(user.friends[i].status==1){
		        newFriends.push(user.friends[i]);
		    }
		}
		user.friends=newFriends;
		detailCb(res, 0, user);
	});
});

function detailCb(res, index, user) {
	if (index == user.friends.length) {
		var length = user.friends && user.friends.length || 0;
		var groups = [];
		for(var i=0; i<length; i++) {
			var group_name = user.friends[i].group || "未分组";
			var find = false;
			for(var j=0; j<groups.length; j++) {
				if(groups[j].name == group_name) {
					if(!groups[j].friends)
						groups[j].friends = [];
					groups[j].friends.push(user.friends[i]);
					find = true;
					break;
				}
			}
			if(find == false) {
				var group = {};
				group.name = group_name;
				group.friends = [];
				if(user.friends[i].id)
					group.friends.push(user.friends[i]);
				groups.push(group);
			}
		}
		user.groups = groups;
		return res.send(resultJson(0, user));
	}

	User.findById(user.friends[index].id, function(err, friend) {
		if (err) {
			logger.error(err);
			return res.send(resultJson(2));
		}
		if (friend) {
			user.friends[index].name = friend.name;
			user.friends[index].phone = friend.phone;
			user.friends[index].category = friend.category;			
			user.friends[index].country = friend.country;		
			user.friends[index].sex = friend.sex;	
			user.friends[index].photo = friend.photo;	
			user.friends[index].education = friend.education;	
			user.friends[index].des = friend.des;										
		}

		index++;
		detailCb(res, index, user);
	});
};

//根据手机号搜索好友
router.post('/shP', function(req, res) {
    var searchPN = req.body.searchInput;
    var category = req.body.category;
    User.find(
   {
      $or: [
         {phone: searchPN}, {name: searchPN}
         ]
   },function(err,searchPN) {
         if (err)
            return res.send(resultJson(2));
          
        if (searchPN.length > 1 || searchPN.length == 0){
            return res.send(resultJson(0));
         }else{
            return res.send(resultJson(0, searchPN));
        }
           
           
            
        });
});


//回复好友验证信息
router.post('/rep',function(req,res){
    var user = req.body.user;
    var friendId = req.body.fid;
    var yz =req.body.yz;
    if (!user || !friendId)
        return res.send(resultJson(3));
    
    var length = user.friends && user.friends.length || 0;
    for(var i=0; i<length; i++) {
        if(user.friends[i].id === friendId)
            return res.send(resultJson(0, user));
    }
    if(yz == 1){
    	User.update({
        _id: user._id,
    }, {
        $addToSet: {
            friends: {
                id: friendId,
                from: user._id,
                status: yz
            },
        },
    }, function(err) {
        if (err)
            return res.send(resultJson(2));

        User.update({
            _id: friendId,
        }, {
            $push: {
                friends: {
                    id: user._id,
                    from: friendId,
                    status: yz,
                    tip: req.body.tip
                },
            },
        }, function(err) {
            if (err)
                return res.send(resultJson(2));
            /*
            var friend = {id: friendId, status:Consts.FRIENDSTATUS.PEDDING};
            if(!user.friends)
                user.friends = [];
            user.friends.push(friend);
            res.send(resultJson(0, user));
            */
            Message.remove({
            	$or: [{
			            from: friendId,
		                 to:user._id,
		                 categroy:1
			        }, {
			            from: user._id,
		                 to:friendId,
		                 categroy:1
			        }],
            }, function(err) {
                if (err)
                return res.send(resultJson(2));
                
             
             if(yz==1){
         	 	User.findOne({
							_id: friendId
					},function(err,friend){
				        if(err){
				          return res.send(resultJson(2));
				        }
				        var mes = friend.category == 30?"我们已经是好友了，可以开始聊天了":"We are friends now, we can start chat.";
						var test =new Object();
		                 test.create = new Date();
		                 test.from=user._id;
		                 test.to=friendId;
		                 test.media=0;
		                 test.categroy=0;
		                 test.content=mes;
		                 new Message(test).save(  function(err,msg){
		                 if(err)
		                 	return res.send(105);

		                 	 User.findOne({
										_id: user._id
								},function(err,user1){
							        if(err){
							          return res.send(resultJson(2));
							        }
							        return res.send(resultJson(0, user1));

								});
			
		              	});

				});
                 
             }
            //return res.send(resultJson(0));
          });   
        });
    });

    }
    if(yz == 2){
    	Message.remove({
                 from: friendId,
                 to:user._id,
                 categroy:1
            }, function(err) {
                if (err)
                	return res.send(resultJson(2));
                return res.send(resultJson(0));
        });
    }
    
});
router.post('/lgn', function(req, res) {
	var phone = req.body.phone;
	var password = req.body.password;
	if (!phone || !password) 
		return res.send(resultJson(3));

	User.find({
		phone: phone,
		password: Utils.MD5(password)
	}, function(err, users) {
		if (err || users.length > 1 || users.length == 0) {
			var cookies = [cookie.serialize(Consts.COOKIE.COOKIE_CODE, "", {
				maxAge: Consts.COOKIE.MAXAGE,
				path: "/"
			})];
			res.setHeader("Set-cookie", cookies);
			logger.error(err);
			return res.send(resultJson(100));
		} else {
			users = JSON.parse(JSON.stringify(users));
			var token = Utils.MD5("" + users[0]._id);
			User.update({
				_id: users[0]._id
			}, {
				$set: {
					token: token
				}
			}, function(err) {
				if (err) {
					logger.error(err);
					return res.send(resultJson(2));
				}
				console.log(token, "token");
				var cookies = [cookie.serialize(Consts.COOKIE.COOKIE_CODE, token, {
					maxAge: Consts.COOKIE.MAXAGE,
					path: "/"
				})];
				res.setHeader("Set-cookie", cookies);
				return res.send(resultJson(0, users));
			})
		}
	});
});


//获取某类型的用户
router.post('/list', function(req, res) {
	var proxy = new EventProxy();
	proxy.all("results", "count", function(results, count) {
		res.send(resultJson(0, {
			results: results,
			count: count
		}))
	})
	var start = req.body.start || 0;
	var count = req.body.count || Consts.MAX;
	var user = req.body;
	var category = user.category || Consts.UTYPE.CHINESE;
	var from = user._user.category; //不需要前端传值
	var query = User.find({
			category: category,
	});
	query.skip(start).limit(count).exec(function(err, users) {
		if (err)
			return res.send(resultJson(100));
		proxy.emit("results", users);
	});
	query.count(function(err, num) {
		if (err)
			return res.send(resultJson(100));
		proxy.emit("count", num);
	});
});

router.post('/upsert', function(req, res) {
	var user = req.body;
	var _id = user._id;
	if(!user.friends)
		user.friends = [];
	if (user._id) {
	    delete user._id;
		User.update({
			_id:_id
		}, {
			$set: user
		}, function(err) {
			console.log(err);
			if (err)
				return res.send(resultJson(2));
			return res.send(resultJson(0));
		});
	} else {
		if (!user.phone)
			return res.send(resultJson(3));

		User.find({
			phone: user.phone
		}).exec(function(err, users) {
			if (err) {
				return res.send(resultJson(2));
			}
			if (users.length != 0)
				return res.send(resultJson(9));

			var newUser = new User(user);
			newUser.save(function(err) {
				if (err)
					return res.send(resultJson(2));
				return res.send(resultJson(0, newUser));
			});
		});

	}
});

router.post("/updatephoto", function(req, res) {
	req.query.updatephoto = true;
	Utils.upload(req, function(json) {
		if (json.code)
			return res.send(resultJson(json.code));

		User.update({
			_id: req.query.id
		}, {
			$set: {
				photo: json.result.url
			}
		}, function(err) {
			if (err)
				return res.send(resultJson(2));
			return res.send(resultJson(0, {
				url: json.result.url
			}));
		});
	});
});


//密码找回短信消息
router.post('/findpwmsg', function(req, res) {
	var phone = req.body.phone;
	User.count({
		phone: phone
	}, function(err, cnt) {
		if (err)
			return res.send(resultJson(2));
		if (cnt){
				var num = Utils.random();
				var msg = "验证码为"+num+"，您正在进行密码找回操作，请勿泄露，如非本人操作，请忽略。【华鑫杰瑞公司】";
				Utils.yanzhengma(phone, msg, function(result) {
					var obj = JSON.parse(result);
					if(obj.result.data == "ok"){
						res.send(resultJson(0, {"type":"ok","phone":phone,"num":num}));
					}
					if(obj.result.data == "error"){
						res.send(resultJson(0, {"type":"error"}));
					}
					
				});
		}else{
			return res.send(resultJson(101));
		}
			
	});
});


//重置密码
router.post('/resetPassword', function(req, res) {
	var phone = req.body.phone;
	var password = req.body.password;
		User.update({
			phone:phone
		}, {
			$set: {
				password: Utils.MD5(password)
			}
		}, function(err) {
			if (err)
				return res.send(resultJson(2));
			return res.send(resultJson(0));
		});
});

//修改密码
router.post('/updatePassword', function(req, res) {
	var user = req.body;
	var _id = user._id;
	var password = user.password;
	var oldPassword = user.oldPassword;
	if (!_id || !password)
		return res.send(resultJson(3));

	User.update({
		_id: _id,
		password: Utils.MD5(oldPassword)
	}, {
		$set: {
			password: Utils.MD5(password)
		}
	}, function(err, result) {
		if (err)
			return res.send(resultJson(2));
		if (result.n > 0)
			return res.send(resultJson(0, Utils.MD5(password)));
		else
			return res.send(resultJson(8));
	});
});

router.post('/remove', function(req, res) {
	var _id = req.body._id;
	if (!_id)
		return res.send(resultJson(3));

	User.remove({
		_id: _id
	}, function(err) {
		if (err)
			return res.send(resultJson(2));
		return res.send(resultJson(0));
	});
});

//增加好友
router.post('/addFriend', function(req, res) {
	var user = req.body.user;
	var friendId = req.body.friendId;
	//1 2
	if (!user || !friendId)
		return res.send(resultJson(3));

	var length = user.friends && user.friends.length || 0;
	for(var i=0; i<length; i++) {
		if(user.friends[i].id === friendId)
			return res.send(resultJson(0, user));
	}

	User.update({
		_id: user._id,
	}, {
		$addToSet: {
			friends: {
				id: friendId,
				from: user._id,
				status: Consts.FRIENDSTATUS.PEDDING
			},
		},
	}, function(err) {
		if (err)
			return res.send(resultJson(2));
		
		User.update({
			_id: friendId,
		}, {
			$push: {
				friends: {
					id: user._id,
					from: user._id,
					status: Consts.FRIENDSTATUS.PEDDING,
					tip: req.body.tip
				},
			},
		}, function(err) {
			if (err)
				return res.send(resultJson(2));

			var friend = {id: friendId, status:Consts.FRIENDSTATUS.PEDDING};
			if(!user.friends)
				user.friends = [];
			user.friends.push(friend);
			res.send(resultJson(0, user));
		});		
	});
});

//更新好友
router.post('/updateFriend', function(req, res) {
	var _id = req.body._id;
	var friendId = req.body.friendId;
	var status = req.body.status;
	if (!_id || !friendId || !status)
		return res.send(resultJson(3));

	User.update({
		_id: _id,
		"friends.id" : friendId
	}, {
		$set: {
			"friends.$.status": status,
			"friends.$.remark": req.body.remark,
		},
	}, function(err) {
		if (err)
			return res.send(resultJson(2));
		
		User.update({
			_id: friendId,
			"friends.id" : _id
		}, {
			$set: {
				"friends.$.status": status
			},
		}, function(err) {
			if (err)
				return res.send(resultJson(2));

			//删除两人之间的聊天记录
			Message.remove({
				$or: [{
					from: friendId,
					to: _id
				}, {
					from: _id,
					to: friendId,
				}],
			}, function(err) {
				return res.send(resultJson(0));
			});
		});		
	});
});


//删除好友
router.post('/delFriend', function(req, res) {
	var _id = req.body._id;
	var friendId = req.body.friendId;
	var status = req.body.status;
	if (!_id || !friendId || !status)
		return res.send(resultJson(3));

	User.update({
		_id: _id,
		"friends.id" : friendId
	}, {
		$pull: {
			friends: {
				id: friendId,
				from: _id,
			},
		},
	}, function(err) {
		if (err)
			return res.send(resultJson(2));
		
		User.update({
			_id: friendId,
			"friends.id" : _id
		}, {
			$pull: {
				friends: {
					id: _id,
					from: friendId,
				},
			},
		}, function(err) {
			if (err)
				return res.send(resultJson(2));

			//删除两人之间的聊天记录
			Message.remove({
				$or: [{
					from: friendId,
					to: _id
				}, {
					from: _id,
					to: friendId,
				}],
			}, function(err) {
				if (err)
					return res.send(resultJson(2));
				User.find({
					_id:_id
				},function(err,user){
					if (err)
						return res.send(resultJson(2));
					return res.send(resultJson(0, user));
				});

			});
		});		
	});
});


//更新组名
router.post('/updateGroupName', function(req, res) {
	var from = req.body.from;
	var to = req.body.to;
	if (!from || !to)
		return res.send(resultJson(3));

	User.update({
		_id: req.body._user._id,
		"friends.group" : from
	}, {
		$set: {
			"friends.$.group": to,
		},
	}, function(err) {
		if (err)
			return res.send(resultJson(2));
		return res.send(resultJson(0));
	});
});
//删除组
router.post('/removeGroupName', function(req, res) {
	var from = req.body.from;
	if (!from)
		return res.send(resultJson(3));

	User.update({
		_id: req.body._user._id,
		"friends.group" : from
	}, {
		$set: {
			"friends.$.group": "未分组",
		},
	}, function(err) {
		if (err)
			return res.send(resultJson(2));
		return res.send(resultJson(0));
	});
});

//新建组
router.post('/newGroupName', function(req, res) {
	var from = req.body.from;
	if (!from)
		return res.send(resultJson(3));

	var friend = {};
	friend.group = from;

	User.update({
		_id: req.body._user._id,
	}, {
		$push: {
			"friends": friend,
		},
	}, function(err) {
		if (err)
			return res.send(resultJson(2));
		return res.send(resultJson(0));
	});
});

//增加或删除组中用户
router.post('/manageGroup', function(req, res) {
	var group_name = req.body.group_name;
	if (!group_name)
		return res.send(resultJson(3));
	
	if(req.body.adds) {
		User.update({
			_id: req.body._user._id,
			"friends.id": req.body.adds
		}, {
			$set: {
				"friends.$.group": group_name,
			},
		}, function(err) {
			if (err)
				return res.send(resultJson(2));
		});		
	}
	if(req.body.removes) {
		User.update({
			_id: req.body._user._id,
			"friends.id": req.body.removes
		}, {
			$set: {
				"friends.$.group": "未分组",
			},
		}, function(err) {
			if (err)
				return res.send(resultJson(2));
		});				
	}
	return res.send(resultJson(0));	
});

//获取用户朋友列表
router.post('/friendlist', function(req, res) {

	var _id = req.body._id;
	if(!_id){
		return res.send(resultJson(3));
	}
	 User.findOne({
			_id: _id,//TODO :这里需要添加条件：好友同意之后方可列出status=1
	},function(err,user1){
        if(err){
          return res.send(resultJson(2));
        }
        user1 = JSON.parse(JSON.stringify(user1));
		getFriendList(res,user1.friends);

	});
	
});
function getFriendList(res,friendList){
	var friendArrs = new Array();
	var count=0;
    for(var i=0;i<friendList.length;i++){
    		User.findOne({
					_id: friendList[i].id,
			},{
				_id:1,
				name:1,
				photo:1,
				phone:1,
			},function(err,user){
		        if(err){
		          return res.send(resultJson(2));
		        }
		       ++count;
		      friendArrs.push(user);
		      
		      if(count==friendList.length){
		      	
 				return res.send(resultJson(0,friendArrs));
		      }
			});
    }

}
module.exports = router;